<template>
  <div class="date-picker">
    <div class="date-picker_toolbar">
      <button type="button" @click="$emit('cancel')" class="toolbar__cancel">
        取消
      </button>
      <div v-if="title" class="toolbar__title">{{ title }}</div>
      <button type="button" @click="_confirm" class="toolbar__confirm">
        确定
      </button>
    </div>
    <div class="date-picker_body">
      <Calendar
        v-model="value"
        visible-type="full"
        :type="type"
        :row-height="32"
        :showBottomArrow="false"
        :allow-same-day="allowSame"
        :formatter="_formatter"
      >
      </Calendar>
    </div>
  </div>
</template>

<script>
import Calendar from "../ll-calendar";
import moment from "moment";
export default {
  props: {
    type: {
      type: String,
      default: "single",
      validator: (val) => {
        return ["single", "range"].includes(val);
      },
    },
    title: {
      type: String,
      default: "",
    },
    allowSame: {
      type: Boolean,
      default: false,
    }, //是否允许日期范围的起止时间为同一天
    //格式化日期
    formatter: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    Calendar,
  },
  data() {
    return {
      value:
        this.type === "single"
          ? moment().format("YYYY-MM-DD")
          : [moment().format("YYYY-MM-DD"), moment().format("YYYY-MM-DD")],
    };
  },
  methods: {
    _confirm() {
      this.$emit("confirm", this.value.length ? this.value : null);
    },
    _formatter(day) {
      if (this.formatter) {
        //传递了formatter:true 开启格式化
        let date = moment(day.date, "YYYY-MM-DD").unix(); //当月每一天时间戳
        let endTime = moment().endOf("days").format("YYYY-MM-DD"); //当前日期
        let endDate = moment(endTime, "YYYY-MM-DD").unix(); //当月当前时间戳
        if (date < endDate) {
          day.type = "disabled";
        }
        return day;
      } else {
        return day;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.date-picker {
  @apply flex flex-col;
  padding-bottom: env(safe-area-inset-bottom);
  .date-picker_toolbar {
    height: 44px;
    @apply flex items-center justify-between;
    .toolbar__cancel,
    .toolbar__confirm {
      height: 100%;
      padding: 0 16px;
      font-size: 14px;
      background-color: transparent;
      border: none;
      cursor: pointer;
    }
    .toolbar__confirm {
      color: #1d6fe9;
    }
    .toolbar__cancel {
      color: #969799;
    }
    .toolbar__title {
      @apply max-w-1/2 font-500 text-16px leading-20px text-center;
    }
  }
  .date-picker_body {
    @apply h-300px;
  }
}
</style>
